package com.apexsoft.monitor.common.http;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

public class JsonResponseHandler implements ResponseHandler<JSONObject> {
	private Charset charset = Charset.forName("UTF-8");

	public JsonResponseHandler(String charset) {
		super();
	}

	public JsonResponseHandler() {
		super();
	}

	@Override
	public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = response.getEntity();
			String resStr = EntityUtils.toString(entity, charset);
			try {
				return JSONObject.parseObject(resStr);
			} catch (JSONException e) {
				throw new ServerErrorException("响应报文数据异常\n" + resStr,e);
			}
		} else {
			throw new ServerErrorException("响应报文状态码异常:" + response.getStatusLine().getStatusCode());
		}
	}
}
